import { Request, Response } from 'express';
import { UserModel } from '../models/user'
import { DictTypeModel } from '../models/dictType'
import { DictDataModel  } from '../models/dictData'
export class DictDataController {
  private userModel: UserModel;
  private dictTypeModel: DictTypeModel;
  private dictDataModel: DictDataModel;
  constructor() {
    this.userModel = new UserModel();
    this.dictTypeModel = new DictTypeModel();
    this.dictDataModel = new DictDataModel();
  }
  add = async (req: Request, res: Response): Promise<void> => {
    try {
      const user = req.user!;
      const { dict_id, dict_value, dict_label, remark, sort } = req.body;
      const result = await this.dictDataModel.create({ dict_id, dict_value, dict_label, sort, remark, create_by: user.userId, update_by: user.userId });
    if (result) {
        res.json({ message: '添加成功', code: 200 });
      } else {
        res.status(200).json({ code: 400, message: '添加失败' })
      }
    } catch (error) {
      res.status(200).json({ code: 500, message: error });
    }
  }
  delete = async (req: Request, res: Response): Promise<void> => {
    try {
      const { ids } = req.body;
      const user = req.user!;
      let result
      if (user.isAdmin) {
        result = await this.dictDataModel.delete(ids);
      } else {
        result = await this.dictDataModel.delete(ids, user.userId);
      }
      if (result) {
        res.json({ message: '删除成功', code: 200 });
      } else {
        res.status(200).json({ code: 400, message: '删除失败'})
      }
    } catch (error) {
      res.status(200).json({ code: 500, message: error });
    }
  }
  findByDictId = async (req: Request, res: Response): Promise<void> => {
    try {
      const { dict_id } = req.query;
      const result = await this.dictDataModel.findByDictId(Number(dict_id));
      const createUserNames = await this.userModel.getUsersByUserIds(result.map(item => item.create_by))
      const upDateUserNames = await this.userModel.getUsersByUserIds(result.map(item => item.update_by))
      const dictInfos = await this.dictTypeModel.findById(Number(dict_id));
      const relUserNames = new Map();
      createUserNames.forEach(item => {
        relUserNames.set(item.userId, item)
      })
      const dictInfo = dictInfos[0] || {}
      upDateUserNames.forEach(item => {
        if (relUserNames.has(item.userId)) return;
        relUserNames.set(item.userId, item)
      })
      const resdata = result.map(item => {
        return {
          ...item,
          create_by: relUserNames.get(item.create_by)?.username,
          update_by: relUserNames.get(item.update_by)?.username,
          type_code: dictInfo.type_code
        }
      })
      res.json({ code: 200, message: '查询成功', data: resdata });
    } catch (error) {
      res.status(200).json({ code: 500, message: error });
    }

  }
  findByCodes = async (req: Request, res: Response): Promise<void> => {
    try {
      const { codes } = req.body;
      const dicts = await this.dictTypeModel.findByCodes(codes as string[]);
      const result = {}
      for (let i = 0; i < dicts.length; i++) {
        const dictData = dicts[i];
        const dictVals = await this.dictDataModel.findByDictId(dictData.id);
        if (dictVals.length === 0) {
          result[dictData.type_code] = []
          continue;
        };
        const createUserNames = await this.userModel.getUsersByUserIds(dictVals.map(item => item.create_by))
        const upDateUserNames = await this.userModel.getUsersByUserIds(dictVals.map(item => item.update_by))
        const relUserNames = new Map();
        createUserNames.forEach(item => {
          relUserNames.set(item.userId, item)
        })
        upDateUserNames.forEach(item => {
          if (relUserNames.has(item.userId)) return;
          relUserNames.set(item.userId, item)
        })

        result[dictData.type_code] = {
          ...dictData,
          dict_vals: dictVals.map(item => {
            return {
              ...item,
              create_by: relUserNames.get(item.create_by)?.username,
              update_by: relUserNames.get(item.update_by)?.username,
              type_code: dictData.type_code
            }
          })
        };
      }
      res.json({ code: 200, message: '查询成功', data: result });
    } catch (error) {
      res.status(200).json({ code: 500, message: error });
    }
  }
  update = async (req: Request, res: Response): Promise<void> => {
    try {
      const user = req.user!;

      const { id, dict_value, dict_label, remark, sort } = req.body;
      await this.dictDataModel.update({ id, dict_value, dict_label, remark, sort, update_by: user.userId });
      res.json({ message: '更新成功', code: 200 });
    } catch (error) {
      res.status(200).json({ code: 500, message: error });
    }
  }
}